<?php

namespace app\api\controller;
use app\common\controller\Api;
// use app\api\model\Homework;
use app\admin\model\GradeClass;
use app\admin\model\User;
use app\api\model\Homework;
use app\api\model\RecitingMission;
use app\api\model\RecitingQuestionAnswer;
use think\Db;
use think\Request;

class NewHomework extends Api
{

    protected $noNeedLogin = ["*"];
    protected $noNeedRight = ['*'];

    // 1听说2听力3跟读4笔试5音标6典范7新概念8黑布林
    // 定义表名数组
    protected $productarr = [
        1=>'hear_say',
        2=>'listening',
        3=>'repeat',
        4=>'writing',
        5=>'soundmark',
        6=>'model',
        7=>'new_concept',
        8=>'_black_plum',
        9=>'textbook_synchronization'
    ];

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->model = new Homework();
    }

    /**
     * 获取教材表名
     */
    protected function products_dbname($ptype){
        
        if(!isset($this->productarr[$ptype])) 
            $this->error('数据[ptype]字段异常');

        return $this->productarr[$ptype] . '_products';
    }

    /**
     * 获取考试资源表名
     */
    protected function resources_dbname($ptype){
        
        if(!isset($this->productarr[$ptype])) 
            $this->error('数据[ptype]字段异常');

        return $this->productarr[$ptype] . '_resources';
    }

    /**
     * 班级列表
     */
    public function teacher_class_list()
    {
        $user = $this->auth->getUser();
        $list = GradeClass::select();
        $class = [];
        $class[] = [
            'id' => 0,
            'class_name' => '全部',
        ];
        foreach($list as $vo){
            $class[] = [
                'id' => $vo->id,
                'class_name' => $vo->grade_name,
            ];
        }
        $this->success('请求成功',$class);
    }

    /**
     * 教师端-重做
     * RecitingMission fa_reciting_mission 
     * RecitingQuestionAnswer fa_reciting_question_answer
     */
    public function teacher_homework_redo()
    {
        $id = input('id/d');
        if (!$id) $this->error('参数错误');

        Db::startTrans();
        try {
            RecitingMission::where('mission_id', $id)->delete();
            RecitingQuestionAnswer::where('mission_id', $id)->delete();
            // $a;
             // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error('重做失败');
        }

        $this->success('已重做');
        
    }

    /**
     * 撤销
     */
    public function teacher_homework_revoke()
    {
        $id = input('id/d');
        if (!$id) $this->error('参数错误');

        Db::startTrans();
        try {
            $this->model->where('id', $id)->delete($id);
            RecitingMission::where('mission_id', $id)->delete();
            RecitingQuestionAnswer::where('mission_id', $id)->delete();
             // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error('撤销失败');
        }

        $this->success('已撤销');
    }

    /**
     * 教师端修改截止时间
     */
    public function teacher_homework_edit_deadlinetime()
    {
        $id = input('id/d');
        if (!$id) $this->error('参数错误');

        $endTime = input('end/s');  // 截止时间

        $item = $this->model->get($id);
        if(!$item) $this->error('任务不存在');


        $endTime = strtotime($endTime);

        if($endTime < strtotime($item->createtime))
            $this->error('截止时间不能小于开始时间');


        $item->deadlinetime = date("Y-m-d H:i:s", $endTime);

        $item->save();

        $this->success('修改成功');
       
    }

    /***
     * 教师端课后作业列表
     * 
     * startTime    作业开始时间
     * isend 已结束
     * name 标题
     * type  0=不选课后作业默认 1=练习 2=测试
     * cname    作业成员
     * pname        来源书籍
     * deadlinetime 截止时间
     * option  repair:截止后可补交
     * shiti_list   试题列表
     * 
     *      tname 题目
     *      all_num  总人数
     *      do_num 已完成人数
     * 
     */
    
    public function teacher_homework_list()
    {
        
        $cid = input('cid/d'); //班级ID
        $time = input('time/s');  // 时间范围
        $endTime = input('end/s');  // 截止时间
        $type = input('type/n');  // 2 机房考试
        $page = input('page/d')&&is_numeric(input('page/d')) ? input('page/d') : 1;
        $pageSize = input('pageSize/d')&&is_numeric(input('pageSize/d')) ? input('pageSize/d') : 10;

        if($time && !strpos($time, ' - '))
            $this->error('参数错误');
        
        [$start, $end] = [0, 0];
        if($time) [$start, $end] = explode(' - ', $time);

        $where = [];

        if(!$this->auth->id)
            $this->error('未登录');

        $where['uid'] = $this->auth->id;
        
        $where['operation'] = 1;

        if($type == 2) $where['operation'] = 2;
        
        if ($cid > 0) {
            $where['cid'] = $cid;
          
        }
        if ($start && $end) {
            $where['startTime'] = ['between',[$start, $end]];
        }
            
        if($endTime){
            $where['deadlinetime'] = ['<=', $endTime];
        }
        // 'checkinfo', 'checkanswer', 'checkscore', 'checksw', 'repair', 'lowfullbi', 'lowfullci', 'percentage', 'frequency',
        $list = $this->model->where($where)->order('id', 'desc')->paginate($pageSize)->each(function($item, $key){
            $item->visible(['id','startTime','name', 'type',  'deadlinetime', 'cname', 'isend', 'pname', 'shiti_list', 'option']);

            // 班级信息
            $GradeClassInfo = GradeClass::get($item['cid']);
            
            // 作业成员 班级年级
            $item->data('cname', $GradeClassInfo ? $GradeClassInfo->gradeName : '未知');

            $item->data('option', [
                ['checkinfo' => $item->checkinfo],
                ['repair' => $item->repair],
                ['checkanswer' => $item->checkanswer],
                ['checkscore' => $item->checkscore],
                ['checksw' => $item->checksw],
                ['lowfullbi' => $item->lowfullbi],
                ['lowfullci' => $item->lowfullci],
                ['percentage' => $item->percentage],
                ['frequency' => $item->frequency],
            ]);
            // 时间修改未提交时间
            $item->data('startTime', $item->createtime);
            
            // 是否结束
            $item->data('isend', strtotime($item['deadlinetime']) <= time());
            
            $shitiinfo = $this->shiti_info($item, ['do_num', 'all_num', 'tname', 'pid']);

            if(!($pid = $item['pid']))
            if(isset($shitiinfo[0]['pid'])) $pid = $shitiinfo[0]['pid'];
            // gradeName
            $whereField = 'productId';
            $field = 'productName';
            if($item['ptype'] == 9) {
                $whereField = 'book_id';
                $field = 'gradeName';
            }
            // 来源书籍
            $item->data('pname', isset($shitiinfo[0]['pname'])?$shitiinfo[0]['pname']:'');

            $item->data('shiti_list', $shitiinfo);
        });
      

        $this->success('请求成功', $list);
    }

   

    /**
     * 获取试题信息
     * 
     * tname 题目
     * all_num  总人数
     * do_num 已完成人数
     */
    protected function shiti_info($item, $typeArr = ['do_num', 'all_num', 'tname'], $tid = 0)
    {
        if ($item['ridjson']) {
            $ridarr = json_decode($item['ridjson'],true);
            $shitiarr = [];
            foreach ($ridarr as $vs) {
                
                if(is_numeric($tid) && $tid > 0 && $tid != $vs['tid']) continue;
                
                $ds = [];

                if(is_array($typeArr) && in_array('tid', $typeArr)){
                    $ds['tid'] = $vs['tid'];
                }

                if(is_array($typeArr) && in_array('pid', $typeArr)){
                    $ds['pid'] = $vs['pid'];
                }

                if(is_array($typeArr) && in_array('do_num', $typeArr)){
                    $donum = RecitingMission::where(['mission_id'=>$item['id'], 'is_done' => 1])->group('user_id')->count();
                    $ds['do_num'] = $donum;
                }
                
                
                if(is_array($typeArr) && in_array('all_num', $typeArr)){
                    $ds['all_num'] = $item['uidarr'] ? count(explode(',',$item['uidarr'])) : User::where('class_id', $item['cid'])->count();
                }
                
                if(is_array($typeArr) && in_array('info', $typeArr)){

                    $whereField = 'versionId';
                    if($item['ptype'] == 9) {
                        $whereField = 'unitid';
                    }

                    // 试题详情
                    $ds['resources'] = Db::name($this->resources_dbname($item['ptype']))->where($whereField,$vs['tid'])->select();

                    $whereField = 'productId';
                    $field = 'productName';
                    if($item['ptype'] == 9) {
                        $whereField = 'versionId';
                        $field = 'book_name';
                    }
                    // 书籍详情
                    $ds['products'] = Db::name($this->products_dbname($item['ptype']))->where($whereField, $item['pid'])->find();
                }
                if(is_array($typeArr) && in_array('tname', $typeArr)){
                    $whereField = 'productId';
                    $field = 'productName';
                    if($item['ptype'] == 9) {
                        $whereField = 'versionId';
                        $field = 'book_name';
                    }
                    // 书籍详情
                    $ds['pname'] = Db::name($this->products_dbname($item['ptype']))->where($whereField, $vs['pid'])->value($field);

                    // 试题详情
                    $ds['tname'] = Db::name($this->resources_dbname($item['ptype']))->where('versionId',$vs['tid'])->value('resourceName');
                }
                if(is_array($typeArr) && in_array('tlist', $typeArr)){
                    $ds['ti'] = is_array($vs['ti']) ? $vs['ti'] : explode(',', $vs['ti']);
                }
                
                $shitiarr[] = $ds;
            }
        }
        return $shitiarr ?? [['do_num' => 0, 'all_num' => 0]];
    }


    /**
     * 教师端作业详情-未完成作业名单
     */
    public function teacher_homework_incomplete()
    {
        $id = input('id/d');
        if (!$id) $this->error('参数错误');

        $item = $this->model->get($id);
        if(!$item) $this->error('任务不存在');

        
        $RecitingMissionWhere = ['mission_id'=> $id, 'is_done' => 1 ];
        $RecitingMissionWhere = ['mission_id'=> $id];
        
        $uidarr = explode(',',$item['uidarr']);

        if(count($uidarr) > 0){
            $user_list = User::whereIn('id', $uidarr)->column('nickname', 'id');
        }else{
            $user_list = User::where(['type' => 2, 'class_id' => $item->cid])->column('nickname', 'id');
        }

        $list = RecitingMission::where($RecitingMissionWhere)->column('is_done','user_id');
        
        $incomplete = [];
        foreach($user_list as $userid => $nickname){
            if(!isset($list[$userid]) || $list[$userid] == 2)
            $incomplete[] = $nickname;
        }

        $total = count($incomplete);
        
        $this->success('请求成功', compact('total',"incomplete")); 
    }

    /**
     * 教师端作业详情-优秀学生列表
     */
    public function teacher_homework_excellent_list()
    {
        $id = input('id/d');
        if (!$id) $this->error('参数错误');

        
        $item = $this->model->get($id);
        if(!$item) $this->error('任务不存在');

        $RecitingMissionWhere = ['mission_id'=> $id, 'is_done' => 2 ];
        $RecitingMissionWhere = ['mission_id'=> $id];

        $user_list = User::where(['type' => 2, 'class_id' => $item->cid])->column('nickname,avatar', 'id');

        $list = RecitingMission::where($RecitingMissionWhere)->order('score desc, id desc')->column('score,full_score,user_id','user_id');

        // 学习之星
        $learning_star = [];
        // 积极之星
        $positive_star = [];

        $i = 0;
        foreach($list as $uid => $info){
            $i++;
            if(count($learning_star) < 3) $learning_star[] = $user_list[$uid];

            if(count($positive_star) >= 3) break;

            if(count($list) <= 3){
                $positive_star[] = $user_list[$uid];
            }elseif(count($list) == 4){
                if($i != 1) $positive_star[] = $user_list[$uid];
            }elseif(count($list) == 5){
                if($i > 1) $positive_star[] = $user_list[$uid];
            }elseif(count($list) == 6){
                if($i > 2) $positive_star[] = $user_list[$uid];
            }elseif(count($list) > 6){
                if($i > 3) $positive_star[] = $user_list[$uid];
            }
        }

        $this->success('请求成功', compact('learning_star',"positive_star"));
       
        foreach($user_list as $uid => $user){
            if(isset($list[$uid])){
                if($list[$uid]['full_score'] == $list[$uid]['score']){
                    if(count($learning_star) < 3) $learning_star[] = $user;
                    else $positive_star[] = $user;
                    continue;
                }
                if(count($positive_star) < 3){
                    $scoring_rate = round($list[$uid]['score']/$list[$uid]['full_score']*100);
                    if($scoring_rate >= 60) $positive_star[] = $user;
                }
            }
        }

        // foreach($user_list as $uid => $user){
        //     $positive_star[] = $user;
        //     $positive_star[] = $user;
        // }

        // foreach(['徐峥', '翟天娇', '潘洁仪'] as $nickname)
        //     $learning_star[] = $positive_star[] =[
        //         'username' => $nickname,
        //         'avatar' => 'https://d-xueer.bigchun.com/uploads/20240418/90c71f72f9e8fdd8b1f01a6e51ab596a.jpg',
        //     ];

        $this->success('请求成功', compact('learning_star',"positive_star")); 
    }

    /**
     * 教师端作业详情-成绩汇总
     */
    public function teacher_homework_result_summary()
    {
        $id = input('id/d');
        if (!$id) $this->error('参数错误');

        $info = $this->model->get($id);
        if(!$info) $this->error('信息不存在');

        // 班级信息
        $GradeClassInfo = GradeClass::get($info['cid']);
            
        // 作业成员 班级年级
        $info->data('cname', $GradeClassInfo ? $GradeClassInfo->gradeName : '未知');
        
        $RecitingMissionWhere = ['mission_id'=>$info['id']];
        
        $shitiinfo = $this->shiti_info($info, ['tname'])[0];
        
        
        $info->data('tname', isset($shitiinfo['tname']) ? $shitiinfo['tname'] : '未知');
        
        $info->visible(['id', 'createtime', 'cname', 'name', 'tname' ]);


        $full_score = RecitingMission::where($RecitingMissionWhere)->value('full_score');

        $userList = User::where(['type' => 2, 'class_id' => $info->cid])->column('nickname', 'id');
        $list = RecitingMission::where($RecitingMissionWhere)->column('score,full_score,user_id,source_id,question_num,answer_num,is_done,createtime','user_id');


        $user_list = [];

        foreach($userList as $uid => $name){
            if(isset($list[$uid])){
                $mission_info = $list[$uid];
                $user_list[] = [
                    'name' => $name,
                    'score' =>  $mission_info['score'],
                    'full_score' => $mission_info['full_score']
                ];
            }else{

                $user_list[] = [
                    'name' => $name,
                    'score' =>  0,
                    'full_score' => $full_score
                ];
            }
        }

        $this->success('请求成功', compact("info","user_list"));
    }

    /**
     * 教师端作业详情-分数
     */
    public function teacher_homework_detail_score()
    {
        $id = input('id/d');
        if (!$id) $this->error('参数错误');

        $item = $this->model->get($id);
        if(!$item) $this->error('任务不存在');

        $shiti_info = $this->shiti_info($item, ['do_num'])[0];

        $RecitingMissionWhere = ['mission_id'=>$id];

        // 总分数
        $full_score = RecitingMission::where($RecitingMissionWhere)->value('full_score');

        $score = [
            'avg_score' => 0,
            'max_score' => 0,
            'min_score' => 0,
            'pass_rate' => 0,
            'excellent_rate' => 0,
        ];
        
        // 总分数大于0表示有答题数据
        if($full_score > 0)
        {
            // 平均分数
            $avg_score = RecitingMission::where($RecitingMissionWhere)->avg('score');
            // 最高分-最低分
            $max_score = RecitingMission::where($RecitingMissionWhere)->max('score');
            $min_score = RecitingMission::where($RecitingMissionWhere)->min('score');

            // 计算优秀率
            $pass_count = RecitingMission::where($RecitingMissionWhere)->where('score', '>', round($full_score * 0.9))->count();
            // 计算及格分数
            $excellent_count = RecitingMission::where($RecitingMissionWhere)->where('score', '>', round($full_score * 0.6))->count();

            $score['avg_score'] = $avg_score;
            $score['min_score'] = $min_score;
            $score['max_score'] = $max_score;
            $score['pass_rate'] = round($pass_count / $shiti_info['do_num']);
            $score['excellent_rate'] = round($excellent_count / $shiti_info['do_num']);
        }

        $this->success('请求成功',$score); 
    }

    /**
     * 教师端作业详情-图表-分数段分析
     * 
     */
    public function teacher_homework_detail_chart()
    {
        $id = input('id/d');
        if (!$id) $this->error('参数错误');

        $RecitingMissionWhere = ['mission_id'=>$id];

        // $RecitingMissionWhere['is_done'] = 1;

        $chart = [
            '0-20%'   => 0,
            '20-40%'  => 0,
            '40-60%'  => 0,
            '60-80%'  => 0,
            '80-100%' => 0,
        ];
        
        // 总分数
        $full_score = RecitingMission::where($RecitingMissionWhere)->value('full_score');

        $list = RecitingMission::where($RecitingMissionWhere)->column('score');

        foreach($list as $score)
        {
            $scoring_rate = round($score/$full_score*100);

            if($scoring_rate >= 0 && $scoring_rate < 20) $chart['0-20%']++;
            elseif($scoring_rate >= 20 && $scoring_rate < 40) $chart['20-40%']++;
            elseif($scoring_rate >= 40 && $scoring_rate < 60) $chart['40-60%']++;
            elseif($scoring_rate >= 60 && $scoring_rate < 80) $chart['60-80%']++;
            elseif($scoring_rate >= 80) $chart['80-100%']++;
        }
       
        $this->success('请求成功', compact("chart")); 
    }

    /**
     * 教师端作业详情-题型分析
     * 试题类型：听说模考,单词跟读,课文跟读,线上作答,报听写
     */
    public function teacher_homework_detail_analysis()
    {

        $this->error('此接口已被删除');
        $id = input('id/d');
        $tid = input('tid/d');  //试题id
        if (!$id) $this->error('参数错误');

        $RecitingMissionWhere = ['mission_id'=>$id];

        // if($tid) $RecitingMissionWhere['source_id'] = $tid;

        // $item = $this->model->get($id);

        // $census = $this->shiti_info($item, ['tname','tid', 'info', 'tlist']);

        

        $question_analysis = [];

        foreach(explode(',', '听说模考,单词跟读,课文跟读,线上作答,报听写') as $key => $question_type)
            foreach(['score_rate', 'avg_score', 'max_score', 'full_score_rate'] as $type)
            $question_analysis[$key][$question_type][$type] = rand(20,100) . (strpos($type, '_rate') ? '%' : '');

        $question_chart_list = array_map(function($var){
            return array_fill_keys(array_keys($var), array_column($var, 'score_rate')[0]);
        }, $question_analysis);
        $question_chart = [];
        foreach($question_chart_list as $val) $question_chart[array_keys($val)[0]] = array_values($val)[0];
        
        $this->success('请求成功', compact("question_analysis","question_chart")); 
    }

    /**
     * 教师端作业详情-学生成绩
     * 全部学生  对应表格
     */
    public function teacher_homework_detail_achievement()
    {
        $id = input('id/d');
        $tid = input('tid/d');  //试题id
        if (!$id) $this->error('参数错误');

        $RecitingMissionWhere = ['mission_id'=> $id ];

        $item = $this->model->get($id);
        if(!$item) $this->error('任务不存在');
        
        // 总分数
        $full_score = RecitingMission::where($RecitingMissionWhere)->value('full_score');

        $user_list = User::where(['type' => 2, 'class_id' => $item->cid])->column('nickname', 'id');
        $list = RecitingMission::where($RecitingMissionWhere)->column('score,full_score,user_id,source_id,question_num,answer_num,is_done,createtime','user_id');


        $achievement = [];

        foreach($user_list as $uid => $name){
            if(isset($list[$uid])){
                $info = $list[$uid];
                $achievement[] = [
                    'name' => $name,
                    'startTime' => date("m/d H:i", $info['createtime'] ),
                    'schedule' => round($info['answer_num']/$info['question_num']*100) . '%',
                    'score' =>  $info['score'],
                    'full_score' => $info['full_score']
                ];
            }else{

                $achievement[] = [
                    'name' => $name,
                    'startTime' => '-',
                    'schedule' => '0%',
                    'score' =>  0,
                    'full_score' => $full_score
                ];
            }
        }
        
        $this->success('请求成功', compact("achievement")); 
    }

    /**
     * 教师端作业详情-题目统计
     */
    public function teacher_homework_detail_census()
    {
        $id = input('id/d');
        if (!$id) $this->error('参数错误');

        $RecitingMissionWhere = ['mission_id'=>$id];

        $item = $this->model->get($id);

        $census = $this->shiti_info($item, ['tname','tid']);
        foreach($census as &$val){

            $full_score = RecitingMission::where(['mission_id'=>$item['id'], 'source_id' => $val['tid']])->group('user_id')->sum('full_score');
            $val['full_score'] = $full_score;

            $score = RecitingMission::where(['mission_id'=>$item['id'], 'source_id' => $val['tid']])->group('user_id')->sum('score');
            $val['score'] = $score;
        }
        
        $this->success('请求成功', compact("census")); 
    }

    /**
     * 教师端作业详情-题目详情
     */
    public function teacher_homework_detail_question_list()
    {
        $id = input('id/d');
        $tid = input('tid/d'); //题目资源id
        if (!$id) $this->error('参数错误');

        $RecitingMissionWhere = ['mission_id'=>$id];

        if($tid) $RecitingMissionWhere['source_id'] = $tid;

        $item = $this->model->get($id);

        $json = RecitingMission::where(['mission_id'=>$item['id']])->value('json');

        if(!$json) $this->error('回答记录数据不存在');
        $question_info = file_get_contents($json);
        $question_info = json_decode($question_info, true);

        // 总分数
        $full_score = RecitingMission::where($RecitingMissionWhere)->value('full_score');

        $user_list = User::where(['type' => 2, 'class_id' => $item->cid])->column('nickname', 'id');
        $list = RecitingMission::where($RecitingMissionWhere)->column('score,full_score,answer_score_json','user_id');

        $student_list = [];
        // $studentList = [];

        if(isset($question_info['resource']) && isset($question_info['resource']['items']))
        foreach($question_info['resource']['items'] as $key => $item){
            $studentList = [];
            foreach($user_list as $uid => $name){
                if(isset($list[$uid])){
                    $info = $list[$uid];
                    $arr = json_decode($info['answer_score_json'], true)[$key];
                    $studentList[] = [
                        'name' => $name,
                        'myvideosource' => $arr['myvideosource'] ?? $arr['url'] ?? '',
                        // 'myvideosource' => '',
                        'score' =>  $info['score'],
                        'full_score' => $info['full_score']
                    ];
                }else{
    
                    $studentList[] = [
                        'name' => $name,
                        'myvideosource' => '',
                        'score' =>  0,
                        'full_score' => $full_score
                    ];
                }
            }

            $student_list[$key] = ['studentList' => $studentList];
        }
       
        $this->success('请求成功', compact("question_info", "student_list")); 

        // $shitiarr = $this->shiti_info($item, ['tlist'], $tid);
        // if(empty($shitiarr))  $this->error('题目为空');

        // $question_list_arr = $shitiarr[0]['ti'];

        // function ch_num($num) {
        //     $char = array("一","二","三","四","五","六","七","八","九",'十');
        //     if(isset($char[$num])) return $char[$num];
        //     return $num + 1;
        // }

        // // print_r($question_details[0]['ti']);
        // $question_info = [];
        // foreach($question_list_arr as $key => $val){
        //     $question_info[] = [
        //         'ti' => +$val,
        //         'tname' => '第' . ch_num(+$val) . '题',
        //         'score' => rand(3,6),
        //         'full_score' => 6
        //     ];
        // }
        
        // $this->success('请求成功', compact("question_info")); 
    }

    /**
     * 教师端题目详情-题目内容-学生列表
     */
    public function teacher_homework_detail_question_student()
    {
        $this->error('此接口已整合进teacher_homework_detail_question_list');
        // $student_list = [];
        // foreach(['祁晓轩', '王子异', '张雨欣', '裴文宣', '范丞丞'] as $name){
        //     $student_list[] = [
        //         'name' => $name,
        //         // 'startTime' => date("m/d H:i", time() - rand(0, 86400 * 7)),
        //         // 'schedule' => rand(80, 100) . '%',
        //         'score' => rand(20,30),
        //         // 'answer_record' => cdnurl($url,true),
        //         'answer_record' => '',
        //     ];
        // }
        // $this->success('请求成功', compact("student_list"));
    }
    /**
     * 教师端题目详情-题目内容-参考答案
     */
    public function teacher_homework_detail_question_details()
    {
        $id = input('id/d');
        $tid = input('tid/d'); //试题ID
        $ti = input('ti/d'); //试题ID
        if (!$id) $this->error('参数错误');

        $RecitingMissionWhere = ['mission_id'=>$id];

        if($tid) $RecitingMissionWhere['source_id'] = $tid;

        $item = $this->model->get($id);

        $answer_score_json = RecitingMission::where(['mission_id'=>$item['id']])->value('answer_score_json');

        if(!$answer_score_json) $this->error('回答记录数据不存在');

        $question_details = json_decode($answer_score_json, true);

        $this->success('请求成功', compact("question_details"));

        // $question_details_arr = $this->shiti_info($item, ['tlist'], $tid)[0]['ti'];

        // function ch_num($num) {
        //     $char = array("一","二","三","四","五","六","七","八","九",'十');
        //     if(isset($char[$num])) return $char[$num];
        //     return $num + 1;
        // }

        // $question_details = [];

        // if(!in_array($ti, $question_details_arr)) $this->error('tid错误');

        // foreach($question_details_arr as $key => $val){
        //     if($val == $ti){
        //         $question_details = [
        //             'ti' => +$val,
        //             'tname' => '第' . ch_num(+$val) . '题',
        //             'score' => rand(3,6),
        //             'full_score' => 6
        //         ];
        //         break;
        //     }
        // }
        
        // $this->success('请求成功', compact("question_details")); 
    }

    /**
     * 教师端作业详情-板块一
     * 
     * deadlinetime 截止时间
     * name 标题
     * full_score   总分数
     * avg_score   平均分数
     * cname    作业成员-八年级二班
     * do_num    已完成人数
     * all_num    总人数
     * 
     * 
     * pass_rate 计算优秀率
     * excellent_rate 及格率
     */
    public function teacher_homework_detail()
    {
        $id = input('id/d');
        $tid = input('tid/d');  //试题id
        if (!$id) $this->error('参数错误');

        $item = $this->model->get($id);
        if(!$item) $this->error('信息不存在');

        // 班级信息
        $GradeClassInfo = GradeClass::get($item['cid']);
            
        // 作业成员 班级年级
        $item->data('cname', $GradeClassInfo ? $GradeClassInfo->gradeName : '未知');

        $RecitingMissionWhere = ['mission_id'=>$item['id']];

        if($tid) $RecitingMissionWhere['source_id'] = $tid;
        
        // 平均分数
        $avg_score = RecitingMission::where($RecitingMissionWhere)->avg('score');
        $item->data('avg_score', $avg_score);
        // 总分数
        $full_score = RecitingMission::where($RecitingMissionWhere)->value('full_score');
        $item->data('full_score', $full_score ?? 100);
        
        $shiti_info = $this->shiti_info($item, ['do_num', 'all_num'], $tid)[0];
        $item->data('do_num', $shiti_info['do_num']);
        $item->data('all_num', $shiti_info['all_num']);
        
        $item->visible(['id', 'avg_score', 'full_score', 'deadlinetime', 'cname', 'name', 'do_num', 'all_num']);

        $this->success('请求成功',$item);
       
    }


    /**
     * 教师端作业详情-顶部信息二
     * 
     * deadlinetime 截止时间
     * scoring_rate 班级得分率
     * do_num    已完成人数
     * not_num    未完成人数
     */
    public function teacher_homework_detail_info()
    {
        $id = input('id/d');
        $tid = input('tid/d');  //试题id
        if (!$id) $this->error('参数错误');

        $item = $this->model->get($id);
        if(!$item) $this->error('信息不存在');

     
        $RecitingMissionWhere = ['mission_id'=>$item['id']];

        // 总得分
        $score = RecitingMission::where($RecitingMissionWhere)->sum('score');

        // 总分数
        $full_score = RecitingMission::where($RecitingMissionWhere)->sum('full_score');

        // 班级得分率
        $item->data('scoring_rate', $full_score ? round($score/$full_score*100) . '%' : '0%');
        
        $shiti_info = $this->shiti_info($item, ['do_num', 'all_num'], $tid)[0];
        $item->data('do_num', $shiti_info['do_num']);
        $item->data('not_num', $shiti_info['all_num'] - $shiti_info['do_num'] );
        
        $item->visible(['scoring_rate', 'deadlinetime', 'do_num', 'not_num']);

        $this->success('请求成功',$item);
       
    }

    /***
     * 作业统计
     * @return void
     */
    public function homework(){

        $prams = $this->request->param();
        if (empty($prams['class_id'])) $this->error('请选择班级');
        $start = $prams['start']? strtotime($prams['start']) : strtotime(date('Y')-1 ."-01-01");
        $end = $prams['end']? strtotime($prams['end']) : strtotime(date('Y') ."-01-01");
        $type = $prams['type'];
        $where = [];
        $where2 = [];
        $where['operation'] = 1;//课后作业
        if ($start&&$end) {
            $where['deadlinetime'] = ['between',[$start,$end]];
        }
        $where['type'] = 2;//模式：测试
        if ($type) {
            switch ($type) {
                case 1:
                    // 听说模考
                    $where2['module'] = '听说模考';
                    break;
                case 2:
                    // 单词跟读
                    $where2['module'] = '单词跟读';
                    break;
                case 3:
                    // 课文跟读
                    $where2['module'] = '课文跟读';
                    break;
                case 4:
                    // 线上做答
                    $where2['module'] = '线上做答';
                    break;
            }
        }
        $hidarr = Homework::where($where)->column('id');
        if ($hidarr) {
            $where2['mission_id'] = ['in',$hidarr];
        }
        //RecitingMission::where($where2)->
        $data = [
            'count'=>1,
            'average'=>18.9,
            'goal'=>'67%',
            'list'=>[
                [
                    'date'=>"09-14",
                    'people'=>40,
                    'countScore'=>100,
                    'goal'=>"67%",
                    'average'=>'18.9',
                    'tallest'=>27.22,
                    'lowest'=>0,
                ],[
                    'date'=>"10-14",
                    'people'=>40,
                    'countScore'=>100,
                    'goal'=>"67%",
                    'average'=>'18.9',
                    'tallest'=>27.22,
                    'lowest'=>0,
                ],[
                    'date'=>"11-14",
                    'people'=>40,
                    'countScore'=>100,
                    'goal'=>"67%",
                    'average'=>'18.9',
                    'tallest'=>27.22,
                    'lowest'=>0,
                ],[
                    'date'=>"12-14",
                    'people'=>40,
                    'countScore'=>100,
                    'goal'=>"67%",
                    'average'=>'18.9',
                    'tallest'=>27.22,
                    'lowest'=>0,
                ]
            ],
            'linear'=>[
                'date'=>['09-14',"10-14","11-14","12-14"],
                'goal'=>["47%","57%","67%","77%"]
            ],
        ];
        $this->success('请求成功',$data);
    }


    public function machine(){
        $prams = $this->request->param();
        if (empty($prams['class_id'])) $this->error('请选择班级');
        $start = $prams['start']? strtotime($prams['start']) : strtotime(date('Y')-1 ."-01-01");
        $end = $prams['end']? strtotime($prams['end']) : strtotime(date('Y') ."-01-01");
        $data = [
            'count'=>16,
            'countCity'=>1,
            'countSchool'=>2,
            'countGrade'=>13,
            'avgScore'=>18.9,
            'avgCity'=>16.8,
            'avgSchool'=>16.8,
            'avgGrade'=>16.8,
            'list'=>[
                [
                    'date'=>"09-14",
                    'people'=>40,
                    'countScore'=>100,
                    'goal'=>"67%",
                    'average'=>'18.9',
                    'tallest'=>27.22,
                    'lowest'=>0,
                ],[
                    'date'=>"10-14",
                    'people'=>40,
                    'countScore'=>100,
                    'goal'=>"67%",
                    'average'=>'18.9',
                    'tallest'=>27.22,
                    'lowest'=>0,
                ],[
                    'date'=>"11-14",
                    'people'=>40,
                    'countScore'=>100,
                    'goal'=>"67%",
                    'average'=>'18.9',
                    'tallest'=>27.22,
                    'lowest'=>0,
                ],[
                    'date'=>"12-14",
                    'people'=>40,
                    'countScore'=>100,
                    'goal'=>"67%",
                    'average'=>'18.9',
                    'tallest'=>27.22,
                    'lowest'=>0,
                ]
            ]
        ];
        $this->success('请求成功',$data);
    }

}